<?php

namespace App;

use Cache;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;

/**
 * Class Wechat
 * @package App
 */
class Wechat
{
    static $url = [
        'writer' => 'https://fair.jkbanlv.com/login?openId=',
        'shop' => 'https://wechatlt.jkbanlv.com/api/#/?token=',
        'home' => 'https://wechatlt.jkbanlv.com/#/home/?token=',
        'find' => 'https://wechatlt.jkbanlv.com/#/find/?token=',
        'community' => 'https://wechat.jkbanlv.com/community/Community/?token=',
        'game' => 'https://wechat.jkbanlv.com/game?token=',
    ];
    static $shareUrl = [
        'writer' => 'https://fair.jkbanlv.com/login',
        'shop' => 'https://wechatlt.jkbanlv.com/api/#/',
        'home' => 'https://wechatlt.jkbanlv.com/#/home/',
        'find' => 'https://wechatlt.jkbanlv.com/#/find/',
    ];

    const SHOP_URL = "https://wechatlt.jkbanlv.com/api/#/?user=";
    const SIGN_URL = "https://wechat.jkbanlv.com/share/getcode?path=";
    const REDIRECT_URL = "https://wechatlt.jkbanlv.com/#/";
    const WRITER_URL = 'https://fair.jkbanlv.com/login?openId=';
    const NOTIFY_URL = "https://wechat.jkbanlv.com/notify";


    /**
     * 支付配置
     * @return \EasyWeChat\Payment\Application
     */
    static function PayConfig()
    {
        $config = [
            // 必要配置
            'app_id' => env('WECHAT_MYOP_APPID'),
            'mch_id' => env('WECHAT_MYOP_MCH_ID'),
            'key' => env('WECHAT_MYOP_KEY'),   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => public_path('/wechatMyop/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path' => public_path('/wechatMyop/apiclient_key.pem'), // XXX: 绝对路径！！！！

            'notify_url' => self::NOTIFY_URL,     // 你也可以在下单时单独设置来想覆盖它
        ];
        return Factory::payment($config);
    }


    /**
     * 公众号配置
     * @return \EasyWeChat\OfficialAccount\Application
     */
    static function OfficialConfig()
    {
        $config = [
            'app_id' => env('WECHAT_APPID'),
            'secret' => env('WECHAT_SECRET'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => storage_path('wechat.log'),
            ],
        ];

        return Factory::officialAccount($config);
    }


    /**
     * 检查用户是否注册
     * @param $code
     * @return mixed
     */
    static function GetUserInfo($code)
    {
        $appid = env('WECHAT_APPID');
        $secret = env('WECHAT_SECRET');

        //第一步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
        $oauth2 = self::Curl($oauth2Url);
        //accestoken
        $access_token = $oauth2["access_token"];
        //openid
        $openid = $oauth2['openid'];

        //第二步:根据全局access_token和openid查询用户信息
        $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $userinfo = self::Curl($get_user_info_url);

        return $userinfo;
        //打印用户信息

    }


    /**
     * @param $url
     * @return mixed
     */
    static function Curl($url)
    {
        //用curl传参
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //关闭ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);


        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    /**
     * 分享的签名
     * @return array
     */
    static function GetSign($path)
    {
        $appid = env('WECHAT_APPID');
        $secret = env('WECHAT_SECRET');
        $url = self::REDIRECT_URL . $path;
        if (strpos($path, 'fair')) {
            $url = urldecode($path);
        }
//        $url = urldecode($path);
        //缓存内是否存在accessToken。
        $accessToken = Cache::remember('accessToken', 120, function () use ($appid, $secret) {
            //获取access_token的请求地址
            $accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            //请求地址获取access_token
            $accessTokenJson = self::Curl($accessTokenUrl);
            return $accessTokenJson['access_token'];
        });
        //获取jsapi_ticket的请求地址
        $jsapiTicket = Cache::remember('jsapiTicket', 120, function () use ($appid, $secret, $accessToken) {
            $ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
            $jsapiTicketObj = self::Curl($ticketUrl);
            return $jsapiTicketObj['ticket'];
        });

        //随机生成16位字符
        $noncestr = str_random(16);
        //时间戳
        $time = time();
        //拼接string1
        $jsapiTicketNew = "jsapi_ticket=$jsapiTicket&noncestr=$noncestr&timestamp=$time&url=$url";
        //对string1作sha1加密
        $signature = sha1($jsapiTicketNew);
        //存入数据
        $data = [
            'appid' => $appid,
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => $signature,
            'jsapiTicket' => $jsapiTicket,
            'url' => $url,
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone'
            ]
        ];
        //返回
        return $data;
    }


    /**
     * 是否关注公众号
     * @param $open_id
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    static function IsFollow($open_id)
    {
        $app = self::OfficialConfig();
        $lists = $app->user->list();
        return in_array($open_id, $lists['data']['openid']);
    }


    /**
     * @param $user_id
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    static function SendMsg($user_id, $msg)
    {
        if ($open_id = User::where('c_id', $user_id)->value('wx_open_id')) {
            $message = new Text($msg);
            $app = Wechat::OfficialConfig();
            $result = $app->customer_service->message($message)->to($open_id)->send();
            if ($result['errcode'] !== 0 || $result['errmsg'] !== 'ok') {
                if ($result['errcode'] === 45015) {
                    return error('您需要进入公众号,发送消息,才能继续抽奖哦');
                }
                if ($result['errcode'] === 45047) {
                    return error('您需要进入公众号,发送消息,才能继续抽奖哦');
                }
                return error($result['errcode']);
            }
            return success();
        }
        return error('您的数据出错了');
    }

}